package com.nfts.imagepicker;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nfts.imagepicker.adapter.ImageAapter;
import com.nfts.imagepicker.bean.FolderBean;
import com.nfts.imagepicker.view.ListImageDirPopupWindow;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 1、避免内存溢出
 * 根据图片的显示大小压缩图片
 * 使用缓存
 * 2、加载速度快
 * <p/>
 * <p/>
 * Imageloader
 * getView(){
 * url -->BitMap
 * url -->LruCache查找
 * ->找到返回
 * -》找不到 url->Task->TaskQueue发送一个通知去提醒后台轮询线程
 * <p/>
 * }
 * Task->run(){根据url加载图片：
 * 1、获取图片显示的大小
 * 2、使用Options对图片进行压缩
 * 3、加载图片并放入LruCache
 * <p/>
 * }
 * <p/>
 * 后台轮询线程
 * TaskQueue->Task->线程池去执行
 * Handler+Looper+Message
 */
public class MainActivity extends AppCompatActivity {
    @Bind(R.id.gridview)
    GridView mGridView;
    @Bind(R.id.bottom_layout)
    RelativeLayout mbottom_layout;
    @Bind(R.id.dir_name_tv)
    TextView mDirName;
    @Bind(R.id.dir_count_tv)
    TextView mDirCount;

    private List<String> mImages;
    private ImageAapter mImageAapter;

    private File mCurrentDir;
    private int mMaxCount;
    private List<FolderBean> mFolderBeans = new ArrayList<>();
    private ProgressDialog mProgressDialog;

    private ListImageDirPopupWindow mDirPopupWindow;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                mProgressDialog.dismiss();
                data2View();
                initDirPopupWindow();
            }
        }

        
    };

    private void initDirPopupWindow() {
mDirPopupWindow = new ListImageDirPopupWindow(this,mFolderBeans);
        mDirPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                lightOn();
            }
        });

        mDirPopupWindow.setOnDirSelectedListener(new ListImageDirPopupWindow.OnDirSelectedListener() {
            @Override
            public void onSelected(FolderBean folderBean) {
                mCurrentDir = new File(folderBean.getDir());
                mImages =Arrays.asList(mCurrentDir.list(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String filename) {
                        if (filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg") || filename.toLowerCase().endsWith(".png")) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                }));
                mImageAapter = new ImageAapter(MainActivity.this,mImages,mCurrentDir.getAbsolutePath());
                mGridView.setAdapter(mImageAapter);

                mDirCount.setText(mImages.size()+"");
                mDirName.setText(folderBean.getName());
                mDirPopupWindow.dismiss();
            }
        });

    }

    /**
     * 内容区域变亮
     */
    private void lightOn() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1.0f;
        getWindow().setAttributes(lp);
    }

    private void lightOff() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.3f;
        getWindow().setAttributes(lp);
    }

    /**
     * 绑定数据到View
     */
    private void data2View() {
        if (mCurrentDir == null) {
            Toast.makeText(this, "未扫描到任何图片", Toast.LENGTH_SHORT).show();
            return;
        }
        mImages = Arrays.asList(mCurrentDir.list());
        mImageAapter = new ImageAapter(this,mImages,mCurrentDir.getAbsolutePath());
        mGridView.setAdapter(mImageAapter);

        mDirCount.setText(mMaxCount+"");
        mDirName.setText(mCurrentDir.getName());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initDatas();
        initEvent();

    }

    private void initEvent() {
        mbottom_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDirPopupWindow.showAsDropDown(mbottom_layout,0,0);
                lightOff();
            }
        });

    }



    /**
     * 利用ContentProvider扫描手机的所有图片
     */
    private void initDatas() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "存储卡不可用！", Toast.LENGTH_SHORT).show();
            return;
        }
        mProgressDialog = ProgressDialog.show(this, null, "正在加载...");
        new Thread() {
            @Override
            public void run() {
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver cr = MainActivity.this.getContentResolver();
                Cursor cursor = cr.query(mImageUri, null, MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?", new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_MODIFIED);
//                Cursor cursor = cr.query(mImageUri, null,
//                        MediaStore.Images.Media.MIME_TYPE + "=? or "
//                                + MediaStore.Images.Media.MIME_TYPE + "=?",
//                        new String[] { "image/jpeg", "image/png" },
//                        MediaStore.Images.Media.DATE_MODIFIED);
                Set<String> mDirPaths = new HashSet<>();
                while (cursor.moveToNext()) {
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    FolderBean folderBean = null;
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        folderBean = new FolderBean();
                        folderBean.setDir(dirPath);
                        folderBean.setFirstImgPath(path);
                    }
                    if (parentFile.list() == null)
                        continue;

                    int picSize = parentFile.list(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String filename) {
                            if (filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg") || filename.toLowerCase().endsWith(".png")) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    }).length;
                    folderBean.setCount(picSize);
                    mFolderBeans.add(folderBean);
                    if (picSize > mMaxCount) {
                        mMaxCount = picSize;
                        mCurrentDir = parentFile;
                    }


                }
                cursor.close();
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }


}
